using System.Linq;
using NUnit.Framework;

namespace Solver
{
	/// <summary>
	/// Find the sum of all numbers which are equal to the sum of the factorial of their digits.
	/// </summary>
	public class Problem034 : SelfChecker, IProblem
	{
		private readonly int[] factorials_;

		public Problem034()
		{
			factorials_ = new int[10];
			factorials_[0] = 1;
			for (var i = 1; i < factorials_.Length; i++)
				factorials_[i] = i * factorials_[i - 1];
		}

		public int Id
		{
			get { return 34; }
		}

		public string Solve()
		{
			return Enumerable.Range(1, 100000).Sum(n => Curiosity(n)).ToString();
		}

		private int Curiosity(int n)
		{
			if (n < 10) return 0;
			var c = 0;
			var tmp = n;
			while (tmp > 0)
			{
				c += factorials_[tmp % 10];
				tmp /= 10;
			}
			return c == n ? n : 0;
		}

		[Test]
		public override void Check()
		{
			Assert.AreEqual(0, Curiosity(2));
			Assert.AreEqual(145, Curiosity(145));
			Assert.AreEqual(0, Curiosity(146));
			Assert.AreEqual("40730", Solve());
		}
	}
}